package vip.liux.contracts.models.files;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FilenameUtils;
import vip.liux.contracts.shared.enums.file.FileType;
import vip.liux.core.tenant.IMultiTenant;
import vip.liux.domain.entities.auditing.AuditedAggregateRoot;

@Getter
@Entity
@Table(name = "fm_file_descriptors")
public class FileDescriptor extends AuditedAggregateRoot<Long, FileDescriptor> implements IMultiTenant {
    @Column(name = "tenant_id")
    private String tenantId;

    @Setter
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "directory_id")
    private DirectoryDescriptor directory;

    @Column(name = "name", nullable = false)
    private String name;

    @Setter
    @Column(name = "mime_type", nullable = false, length = 128)
    private String mimeType;

    @Setter
    @Column(name = "ext", nullable = false, length = 128)
    private String ext;

    @Setter
    @Column(name = "file_type", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    private FileType fileType;

    @Setter
    @Column(name = "size", nullable = false)
    private Integer size;

    public FileDescriptor() {
        super();
    }

    public FileDescriptor(String name, String mimeType, DirectoryDescriptor directory, Integer size, String tenantId) {
        this.mimeType = mimeType;
        this.size = size;
        this.tenantId = tenantId;

        this.directory = directory; // this is a bug
        setName(name);
        this.ext = FilenameUtils.getExtension(name);
        this.fileType = FileType.getFileType(this.ext);
    }

    protected void setName(String name) {
        this.name = FileNameValidator.checkFileName(name);
    }

    public Long getDirectoryId() {
        return null == directory ? null : directory.getId();
    }
}